package com.hxm.demo.newcoder;

/**
 * description: add a description
 *
 * @author huangxiaoming
 * @version 1.0.0
 * @date 2023/08/25 10:59:39
 */
public class TestBM9 {

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        ListNode listNode = removeNthFromEnd2(head, 2);
        System.out.println(listNode);
    }


    public static ListNode removeNthFromEnd1(ListNode head, int n) {
        // write code here
        if (head == null) {
            return head;
        }
        ListNode fast = head;
        ListNode slow = head;
        ListNode result = slow;
        for (int i = 0; i < n + 1; i++) {
            if (fast == null) {
                if (i == n) {
                    return head.next;
                }
                return head;
            }
            fast = fast.next;
        }
        while (fast != null && slow != null) {
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return result;
    }

    public static ListNode removeNthFromEnd2(ListNode head, int n) {
        // write code here
        ListNode pre = new ListNode(-1);
        pre.next = head;

        ListNode cur = head;
        int k = 0;
        while (cur != null) {
            k++;
            cur = cur.next;
        }

        ListNode res = pre;
        cur = head;
        for (int i = 0; i < k - n; i++) {
            pre = cur;
            cur = cur.next;
        }
        pre.next = cur.next;
        return res.next;
    }
}
